/*
 * Util.cpp
 *
 *   Created on: 2010-1-20     
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../../include/util/Util.h"
#include "../../include/util/JsonRpcException.h"

#include <sys/timeb.h>

#include <errno.h>
#include <string.h>
#include <string>
#include <iostream>
#include <sstream>

using std::cout;
using std::endl;
using std::string;

Util* Util::_instance = NULL;

Util::Util()
{
	//初始化，只允许1个
	sem_init(&_sem_rsaTools, 0, 1);

}

Util::~Util()
{
	//释放mutex
	sem_destroy(&_sem_rsaTools);

	cout << "我结束了" << endl;

}

string Util::getErrMsg()
{
	return string(strerror(errno));
}

Util* Util::getInstance()
{
	if (_instance == NULL)
	{
		_instance = new Util();
	}
	return _instance;
}

void Util::destory()
{
	//实际工作交给～函数
	if (_instance != NULL)
	{
		delete _instance;
	}
}

RSATools* Util::getRSAToolsByIP(const string &ip)
{
	RSATools* ret;
	sem_wait(&_sem_rsaTools);

	map<string, RSATools>::iterator itr = _rsaTools.find(ip);
	if (itr == _rsaTools.end())
	{
		//没有找到
		ret = NULL;
	}
	else
	{
		//找到，返回地址
		ret = new RSATools(itr->second);
	}

	sem_post(&_sem_rsaTools);

	return ret;
}

RSATools* Util::generateRSAToolsByIP(const string &ip)
{
	//关键区开始
	sem_wait(&_sem_rsaTools);

	//直接更新
	RSATools *rsa = new RSATools();
	_rsaTools[ip] = *rsa;

	//关键区结束
	sem_post(&_sem_rsaTools);

	return rsa;//返回的只是副本
}

string Util::getFormatTime()
{
	timeb time;
	if (-1 == ftime(&time))
	{
		return string();
	}
	else
	{
		//获取成功，转化为时间
		struct tm *now = localtime(&time.time);
		std::ostringstream ss;
		ss << (now->tm_year + 1900) << "-" << (now->tm_mon + 1) << "-"
				<< now->tm_mday << " " << now->tm_hour << ":" << now->tm_min
				<< ":" << now->tm_sec << " " << time.millitm;

		return ss.str();
	}
}

string Util::replaceLine(const string& str)
{
	string tmp(str);

	string::iterator itr = tmp.begin();
	string::size_type pos = 0;
	while (true)
	{
		pos = tmp.find_first_of("\n\r", pos);
		if (pos != string::npos)
		{
			tmp = tmp.replace(pos, 1, "\\n");
		}
		else
		{
			break;
		}
	}

	return tmp;
}
